﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using WLG.Model.Permissions;
using System.Xml;
using System.Xml.Linq;

namespace WLG.NotifyLiveDataProvider.SocialFeed
{
    static class NotificationAdapter
    {
        private const string NOTIFY_API_URL = "http://sup.live.com/whatsnew/whatsnewservice.asmx";
        private const string requestXml = "<?xml version=\"1.0\" encoding=\"utf-8\"?><soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"><soap:Header><WNApplicationHeader xmlns=\"http://www.msn.com/webservices/AddressBook\"><ApplicationId>3B119D87-1D76-4474-91AD-0D7267E86D04</ApplicationId></WNApplicationHeader><WNAuthHeader xmlns=\"http://www.msn.com/webservices/AddressBook\"><TicketToken>{0}</TicketToken></WNAuthHeader></soap:Header><soap:Body><GetContactsRecentActivity xmlns=\"http://www.msn.com/webservices/AddressBook\"><entityHandle><Cid>{1}</Cid></entityHandle><locales><string>en-US</string></locales><count>1</count></GetContactsRecentActivity></soap:Body></soap:Envelope>";



        public static Uri GetNotificationsFeedUrl(Identity oId)
        {
            string result = "";

            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(NOTIFY_API_URL);
            string ticket = oId.Ticket[new Uri("http://sup.live.com/whatsnew/whatsnewservice.asmx")];
            string cID = oId.CID;

            cID = System.Int64.Parse(oId.CID, System.Globalization.NumberStyles.AllowHexSpecifier).ToString();
            //Get ticket for storage service.
        
            byte[] postData = new UTF8Encoding(false).GetBytes(String.Format(requestXml, ReplaceInvalidXMLChars(ticket), ReplaceInvalidXMLChars(cID)));

            //request.Headers.Add("Authorization", "WLID1.0 " + ticket);
            request.AllowAutoRedirect = false;
            request.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; Trident/4.0; SLCC1; .NET CLR 2.0.50727; InfoPath.2; .NET CLR 3.5.21022; .NET CLR 3.5.30729; .NET CLR 3.0.30618; OfficeLiveConnector.1.3; OfficeLivePatch.1.3)";
            request.ContentType = "text/xml";
            request.ProtocolVersion = HttpVersion.Version11;
            request.Method = "POST";
            using (Stream requestStream = request.GetRequestStream())
            {
                requestStream.Write(postData, 0, postData.Length);
            }

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();

            StreamReader loResponseStream = new
                  StreamReader(response.GetResponseStream());

            result = loResponseStream.ReadToEnd();

            loResponseStream.Close();
            response.Close();


            using (StringReader sr = new StringReader(result))
            {
                using (XmlTextReader xTR = new XmlTextReader(sr))
                {
                    XDocument doc = XDocument.Load(xTR, LoadOptions.None);


                    XElement c = (from moniker in doc.Root.DescendantsAndSelf()
                            where moniker.Name.LocalName.ToLower() == "feedurl"
                            select moniker).FirstOrDefault<XElement>();
                    return new Uri(c.Value);
                }
            }
            return null;
        }

        public static string ReplaceInvalidXMLChars(string inString)
        {
            inString = inString.Replace("<", "&lt;");
            inString = inString.Replace(">", "&gt;");
            inString = inString.Replace("\"", "&quot;");
            inString = inString.Replace("'", "&apos;");
            inString = inString.Replace("&", "&amp;");

            return inString;
        }
    }
}
